/* ========================= */
/*        autoresize         */

var HooResize = new Class ({
	options: {
		minheight: 5,
		maxheight: false,
		linelength: 80,
		keyup: function() {}
	},
	
	initialize: function(element, options) {
		this.element = element;
		var fontSize = this.element.getStyle('font-size').toInt();
		alert(fontSize);
		var elWidth = this.element.getStyle('width').toInt();
		var elHeight = this.element.getStyle('height').toInt();
		if (!isNaN(fontSize) && fontSize > 0) {
			if (!isNaN(elWidth) && elWidth > 0) {
				this.options.linelength = Math.floor(elWidth / fontSize * 1.5);
			}
			if (!isNaN(elHeight) && elHeight > 0) {
				this.options.minheight = Math.floor(elHeight / fontSize) - 1;
				if (this.options.minheight < 1) this.options.minheight = 1; 
				if (this.options.maxheight != false && this.options.maxheight < this.options.minheight) this.options.maxheight = this.options.minheight; 
			}			
		}
		this.setOptions(this.options, options);
		this.element.addEvents({
			keyup: this.onKeyUp.bindWithEvent(this)
		});	
	},
	
	onKeyUp: function () {
	    var cols = this.options.linelength;
	    var content = this.element.value ;
	    var lineCount = 0 ;
	    var lastEOL = -1 ;   
	    do {
	        var begin = lastEOL+1 ;
	        lastEOL = content.indexOf("\n",lastEOL+1) ;
	        var line = "" ;
	        if(lastEOL != -1) {
	            line = content.substring(begin, lastEOL) ;
	        } else {
	            line = content.substring(begin, content.length) ;
	        }
	        var rows_in_line = Math.floor(line.length/cols)+1 ;
	        lineCount += rows_in_line;
	    } while (lastEOL != -1) ;
	    if (lineCount < this.options.minheight) {
	    	lineCount = this.options.minheight;
	    } else if (this.options.maxheight && lineCount > this.options.maxheight) {
	    	lineCount = this.options.maxheight;
	    }
	    //lineCount = lineCount < this.options.minheight?this.options.minheight:(lineCount > this.options.maxheight?this.options.maxheight:lineCount);
	    this.element.rows = lineCount ;		
	}
});

Element.implement({
    HooResize: function(options){
        return new HooResize(this, options);
    }
});

HooResize.implement(new Events);
HooResize.implement(new Options);